﻿//-----------------------------------------------------------------------
// <copyright file="Program.cs" company="Ucodia">
//     Copyright © Ucodia. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------

using System;
using System.Configuration;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using Microsoft.Win32;

namespace Ucodia.LocaliZune
{
    /// <summary>
    /// LocaliZune console application.
    /// </summary>
    internal class Program
    {
        /// <summary>
        /// Registry key name.
        /// </summary>
        private const string KeyName = @"HKEY_CURRENT_USER\Control Panel\International\Geo";

        /// <summary>
        /// Registry value name.
        /// </summary>
        private const string ValueName = "Nation";

        /// <summary>
        /// LocaliZune exe configuration object.
        /// </summary>
        private static Configuration configuration;

        /// <summary>
        /// LocaliZune configuration section.
        /// </summary>
        private static LocaliZuneConfigurationSection configurationSection;

        /// <summary>
        /// LocaliZune console entry point.
        /// </summary>
        private static void Main()
        {
            // Variable initialization
            string currentNationCode = string.Empty;
            string newNationCode = string.Empty;
            string applicationFilePath = string.Empty;
            int shutdownDelay = 3;
            bool registryModified = false;
            Process application = new Process();

            try
            {
                // Getting current nation code from registry
                currentNationCode = Registry.GetValue(KeyName, ValueName, null) as string;
                Console.WriteLine("Current nation code is {0}", currentNationCode);

                // Check if Zune Software is not already launched
                if (Process.GetProcesses().Count(p => p.ProcessName == "Zune") != 0)
                {
                    throw new InvalidOperationException("Zune Software is already launched.\n" + 
                                                        "Close the Zune Software, wait 30 seconds and restart LocaliZune.");
                }

                // Loading configuration
                configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                configurationSection = configuration.GetSection(LocaliZuneConfigurationSection.LocaliZuneConfigurationSectionSectionName) as LocaliZuneConfigurationSection;

                // Checking if configuration has been correctly loaded
                if (configurationSection == null)
                {
                    throw new InvalidOperationException("Configuration section is missing from configuration file.");
                }

                // Check string configuration setting integrity
                if (configurationSection.Account.NationCode == string.Empty || 
                    configurationSection.Software.ApplicationPath == string.Empty)
                {
                    throw new InvalidOperationException("Application settings are missing from configuration file.");
                }

                // Setting local variables from configuration
                newNationCode = configurationSection.Account.NationCode;
                applicationFilePath = configurationSection.Software.ApplicationPath;
                shutdownDelay = configurationSection.Settings.ShutdownDelay;

                // Setting new nation code to registry
                Registry.SetValue(KeyName, ValueName, newNationCode);
                Console.WriteLine("Nation code has been changed to {0}", newNationCode);
                registryModified = true;

                // Starting the application
                Console.WriteLine("Launching Zune...", newNationCode);
                application.StartInfo.FileName = applicationFilePath;
                application.Start();

                // Waiting for application initialization
                Console.WriteLine("Waiting for Zune to start...");
                Thread.Sleep(shutdownDelay * 1000);
            }
            catch (Exception e)
            {
                Console.WriteLine("\n---------- ERROR ----------\n");

                // Display error message
                Console.WriteLine(e.Message);
                Console.WriteLine("\nPress any key to exit...");
                Console.ReadKey();
            }
            finally
            {
                if (currentNationCode != string.Empty && registryModified)
                {
                    // Set back nation code to registry
                    Registry.SetValue(KeyName, ValueName, currentNationCode);
                    Console.WriteLine("Nation code has been changed back to {0}", currentNationCode);             
                }
            }
        }
    }
}
